#!/usr/bin/python
#-*- encoding:utf-8 -*-
#
########################################
# 外部人员登录
#
#######################################
import sys
import os
import cgi
import md5

import base_account
import base_db
import base_debug
import base_template

from global_define import *
import urllib

OA_URL = 'http://passport.oa.com/modules/passport/signout.ashx?';
#oa登录验证
OA_LOGINED = 1;
#外部登录
EXTERNAL_LOGINED = 2;

class ELogin:
    """ 外部登录验证 """
    def __init__(self):
        self.status = -1;
        self.account = base_account.BaseAccount();
        self.oDebug = base_debug.BaseDebug();
        self.oBaseDB = base_db.BaseDB("mqq_secure_db");
        self.oDebug.InfoLog(1, "Login: start");
        if os.environ.has_key('SERVER_NAME'):
            self.serverName = os.environ['SERVER_NAME'];
        else :
            self.serverName = "";
        if os.environ.has_key('REQUEST_URI'):
            self.requestUrl = os.environ['REQUEST_URI'];
        else :
            self.requestUrl = "";
        form = cgi.FieldStorage();
        if form.has_key('action'):
            self.action = int(form['action'].value);
        else :
            self.action = 0;
        if form.has_key('jump_url'):
            self.jumpUrl = form['jump_url'].value;
        else :
            self.jumpUrl = self.requestUrl[:self.requestUrl.index('cgi-bin') + 8] + "mainpage";
    
    def CgiInit(self):
        form = cgi.FieldStorage();
        try:
            self.user_account = str(form['account'].value);
        except:
            self.user_account = '';
        try:
            user_password = str(form['password'].value);
        except:
            user_password = '';
        oMd5 = md5.md5(user_password);
        self.user_password = oMd5.hexdigest();

    def checkPw(self):
        sql_sentence = "select userid from user_info where loginname='${sName}' and passwd='${sPW}' ";
        d = {"sName": self.user_account, "sPW": self.user_password};
        self.oBaseDB.execute_mysqldb(sql_sentence, d);
        row = self.oBaseDB.db_cursor.fetchone();
        if row:
            if not self.account.SetAccount(self.user_account):
                raise LoginError("Login._Process raise exception [%s setAccount fail]." % self.user_account); 
            return True;
        else:
            return False;
    
    def ExternalLogin(self):
        self.CgiInit();
        if self.checkPw() == False:
            self.oDebug.InfoLog(0, "Login:Process: CheckPW fail:[%s][%s]"%(self.user_account, self.user_password))
            self.status = -1
            return True
        self.account.WriteCookie();
        self.account.SetStatus();
        self.account.AddExpire();
        self.status = 0;
        return True;
    def HandleResult(self):
        self.oDebug.InfoLog(1, "Login:HandleResult");
        print """Content-Type: text/html; charset=utf-8""";
        print """Cache-Control: no-cache""";
        if self.status < 0:
            print "";
            print """<html><head></head><body><script>alert('登录失败');top.location.href='%seindex.html';</script></body></html>""" % (g_PagePath);                   
            return True;
        self.oDebug.InfoLog(1, "Login:HandleResult: jump mainpage");
        print """Location: %s\r\n""" % self.jumpUrl;
        #print """<html><head></head><body><script>top.location.href='mainpage'</script></body></html>""";
        return True;
    
    def OaLogined(self):
        '''验证oa登录跳转过来的请求'''
        if self.__CheckTicket():
            self.account.SetAccount(self.user_account);
            self.account.WriteCookie();
            self.account.SetStatus();
            self.account.AddExpire();
            print "Context-type: text/html";
            print "Location: %\r\n" % self.jump_url;
        else :
            self.RedirectOaLogin();

    def RedirectOaLogin(self):
        '''redict 到oa'''
        url = OA_URL + urllib.urlencode({'url': "http://" + self.serverName + self.requestUrl + "?action=1&jump_url=" + self.jumpUrl})
        print "Context-type: text/html";
        print """Cache-Control: no-cache""";
        print "Location: %s\r\n" % url;  

    def RedirectExternalLoginPage(self):
        print "Context-type: text/html";
        print """Cache-Control: no-cache""";
        print "Location: %s\r\n" % ('eindex.html');

    def __CheckTicket(self):
        form = cgi.FieldStorage();
	if form.has_key('ticket'):
            self.ticket = str(form['ticket'].value);
	else :
	    self.ticket = "";
	self.oDebug.InfoLog(0,self.ticket);
        if 0 == len(self.ticket):
            #raise LoginError("Fail: can not get the ticket [ticket length is zero]");
            return False;
        commandstr = "/usr/local/app/apache/oa/decryptticket %s" % self.ticket;
        commandresult = os.popen(commandstr).read();
        if commandresult[0:18] == "DecryptTicket succ":
            returns = commandresult.split('\n');
            names = returns[6].split(':');
            self.user_account = names[1].lstrip();
            self.oDebug.InfoLog(0, "_CheckTicket success");
        else:
            return False;
        return True;

    def Do(self):                       
        try:
	    self.oDebug.InfoLog(0,self.serverName + "_test");
	    self.oDebug.InfoLog(0,'test');
	    self.oDebug.InfoLog(0,str(self.serverName.find('wsd.com')));
	    self.oDebug.InfoLog(0,str(self.action));
            if self.serverName.find('wsd.com') or self.serverName.find('3gqq.com'):
		self.oDebug.InfoLog(0,'oa login');
                if self.action == OA_LOGINED:
		    self.oDebug.InfoLog(0,'oa check');
                    self.OaLogined();
                else :
		    self.oDebug.InfoLog(0,'oa redirect');
                    self.RedirectOaLogin();
            else:
                if self.action == EXTERNAL_LOGINED:
                    self.ExternalLogin();
                    self.HandleResult();
                else :
                    self.RedirectExternalLoginPage();
        except Exception,e:
	    self.oDebug.InfoLog(0,e);
            self.status = -1;
            self.HandleResult();
if __name__ == "__main__":
    _elogin = ELogin();
    _elogin.Do();

